package com.xyz.rok.tools.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xyz.rok.tools.constant.Task;
import com.xyz.rok.tools.model.Command;
import com.xyz.rok.tools.model.Result;
import com.xyz.rok.tools.model.Union;
import com.xyz.rok.tools.model.User;
import com.xyz.rok.tools.model.request.UnionRequest;
import com.xyz.rok.tools.model.response.UserResponse;
import com.xyz.rok.tools.service.CommandService;
import com.xyz.rok.tools.service.UnionService;
import com.xyz.rok.tools.service.UserService;
import com.xyz.rok.tools.service.WxAppService;
import com.xyz.rok.tools.utils.JwtUtil;
import com.xyz.rok.tools.utils.TokenPayload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ZhangYiXin
 * @version 1.0
 * @date 2021/4/13 18:26
 **/
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {
    private final String AUTHORIZATION_CODE = "authorization_code";
    private ObjectMapper mapper = new ObjectMapper();
    @Autowired
    private WxAppService wxAppService;
    @Value("${weixin.appid:}")
    private String appId;
    @Value("${weixin.secret:}")
    private String secret;
    @Autowired
    private UserService userService;
    @Autowired
    private CommandService commandService;
    @Autowired
    private UnionService unionService;
    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/code2Session")
    public Result code2Session(@RequestParam("code") String jsCode) throws JsonProcessingException {
        Map<String, String> response = mapper.readValue(wxAppService.code2Session(appId, secret, jsCode, AUTHORIZATION_CODE), Map.class);
        User user = new User();
        user.setOpenId(response.get("openid"));
        user.setUnionId(response.get("unionid"));
        user.setSessionKey(response.get("session_key"));
        User u = userService.addOrUpdate(user);
        UserResponse ur = new UserResponse();
        BeanUtils.copyProperties(u, ur);
        List<Long> unionIds = new ArrayList();
        List<Union> unions = unionService.selectUnionByUserId(u.getId());
        for (Union union : unions) {
            unionIds.add(union.getId());
        }
        TokenPayload tokenPayload = new TokenPayload();
        tokenPayload.setUserId(u.getId());
        tokenPayload.setUnionIds(unionIds);
        Map<String, Object> map = new HashMap<>(8);
        map.put("user", ur);
        map.put("token", jwtUtil.createToken(tokenPayload));
        return Result.success(map);
    }

    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
        return Result.success(userService.selectByPrimaryKey((Long) request.getAttribute("userId")));
    }

    @PostMapping("/addTask")
    public Result addTask(@RequestBody UnionRequest unionRequest) throws Exception {
        Command command = new Command();
        command.setName(Task.EXTRACT_UNION_TASK);
        command.setValue(unionRequest.getUnionId().toString());
        return Result.success(commandService.insertSelective(command));
    }
}
